package com.jason.kotlin.meta.architecture2.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.jason.kotlin.meta.architecture2.api.ApiSource
import com.jason.kotlin.meta.architecture2.api.UserService
import com.jason.kotlin.meta.architecture2.model.UserBean
import com.jason.kotlin.meta.architecture2.model.WanDataWrapper
import com.jason.kotlin.meta.architecture2.repository.UserApi
import com.jason.kotlin.meta.architecture2.repository.UserApiImpl
import com.jason.library.common.base.PageStatus
import kotlinx.coroutines.launch
import java.lang.Exception

class UserViewModel(application: Application) : AndroidViewModel(application) {

    //页面状态变化
    val pageStatusData = MutableLiveData<PageStatus>()

    val userData = MutableLiveData<WanDataWrapper<UserBean>>()

    val registerData = MutableLiveData<WanDataWrapper<Any>>()

    val logoutData = MutableLiveData<WanDataWrapper<Any>>()

    private var userApi: UserApi



    init {
        val userService = ApiSource.getWanAndroidService(UserService::class.java)
        userApi = UserApiImpl(userService)
    }


    fun login(username:String, password:String) {
        viewModelScope.launch {
            pageStatusData.postValue(PageStatus.loading())
            try {
                val userResponse = userApi.login(username, password)
                if(userResponse.isSuccess()){
                    userData.postValue(WanDataWrapper.success(userResponse.data))
                }else{
                    userData.postValue(WanDataWrapper.error(userResponse.errorMsg,null))
                }

                pageStatusData.postValue(PageStatus.success())
            }catch (e: Exception) {
                pageStatusData.postValue(PageStatus.error(e.toString()))
            }
        }
    }

    fun register(username:String, password:String, repassword: String) {
        viewModelScope.launch {
            pageStatusData.postValue(PageStatus.loading())
            try {
                val registerResponse = userApi.register(username, password, repassword)
                registerData.postValue(WanDataWrapper.success(registerResponse.data))
                pageStatusData.postValue(PageStatus.success())
            }catch (e: Exception) {
                pageStatusData.postValue(PageStatus.error(e.toString()))
            }
        }
    }

    fun logout() {
        viewModelScope.launch {
            pageStatusData.postValue(PageStatus.loading())
            try {
                val logoutResponse = userApi.logout()
                logoutData.postValue(WanDataWrapper.success(logoutResponse.data))
                pageStatusData.postValue(PageStatus.success())
            }catch (e: Exception) {
                pageStatusData.postValue(PageStatus.error(e.toString()))
            }
        }
    }
}